﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using MQ.Core.Common;
using MQ.Core.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MQ.Core.Admin.Filters
{
    public class ExceptionFilter : IExceptionFilter
    {
        private readonly ILogger<ExceptionFilter> logger;
        public ExceptionFilter(ILogger<ExceptionFilter> logger)
        {
            this.logger = logger;
        }
        public void OnException(ExceptionContext context)
        {
            if (!context.ExceptionHandled)
            {
                if (!context.Exception.Message.IsEmpty())
                {
                    logger.LogError(context.Exception+":"+context.Exception.Message); 
                    context.Result = new JsonResult(ResultMsg.Fail(status: -1, msg: context.Exception + ":" + context.Exception.Message));
                }
                else if (context.Exception.InnerException.IsEmpty())
                {
                    logger.LogError(context.Exception.InnerException.Source + ":" + context.Exception.InnerException.Message);
                    context.Result = new JsonResult(ResultMsg.Fail(status: -1, msg: context.Exception.InnerException.Source+":"+context.Exception.InnerException.Message));
                }
            }
            context.ExceptionHandled = true;
        }
    }
}
